#include "StdAfx.h"
#include "Module.h"
#include "MsgDispatchCenter.h"
#include "NaviService.h"
extern CNaviServiceApp theApp;

//#define WIN_PATH				_T("\\windows\\")
//#define SD_PATH					_T("\\SDMEM\\")
//#define DISK_PATH				_T("\\APP Disk\\APP_MODULE\\")


void SalSendToHal(BYTE *buf, int len)
{
	theApp.m_MsgDispatchCenter.TransformAndSendMsg(0x01,buf,len);
}

CModule::CModule(void)
{
    m_iModuleIndex = 0;
	m_strModulePath = L"";

	pExportInterface_ = NULL;
}

CModule::~CModule(void)
{
}
bool CModule::Module_Init(CString strPrefix)
{
    CString strPath = FindDllPath(strPrefix+L"Module.dll");
	GD_DBG_LOG("module path %s",strPath.GetBuffer());
	if(!LoadDll(strPath))
	{
		GD_LOG(LOG_LVL_ERR,"load dll fail");
		return false;
	}
		
	if (pExportInterface_ && pExportInterface_->Init)
		pExportInterface_->Init(pExportInterface_->handle, &m_iModuleIndex);
	return true;
}
void CModule::Module_InitByConfig()
{
	if (pExportInterface_ && pExportInterface_->InitConfig)
		pExportInterface_->InitConfig(pExportInterface_->handle);
}

void CModule::Module_InitLastStep()
{
	if (pExportInterface_ && pExportInterface_->InitLastStep)
		pExportInterface_->InitLastStep(pExportInterface_->handle);
}

void CModule::Module_DeInit()
{
	if (pExportInterface_ && pExportInterface_->DeInit)
		pExportInterface_->DeInit(pExportInterface_->handle);
}
void CModule::Module_WriteCmd(unsigned char* buf,int len)
{
	if (pExportInterface_ && pExportInterface_->RecvMsg)
		pExportInterface_->RecvMsg(pExportInterface_->handle, buf, len);
}

void CModule::Module_GetMyModuleParam(DWORD dwParamID, void* pParam, int* pParamLen)
{
	if (pExportInterface_ && pExportInterface_->GetSelfData)
		pExportInterface_->GetSelfData(pExportInterface_->handle, dwParamID, pParam, pParamLen);
}

CString CModule::FindDllPath(CString strDllName)
{
	CString sdPath = SD_PATH + strDllName;
	if (-1 != GetFileAttributes(sdPath))
		return sdPath; 

	CString diskPath = DISK_PATH + strDllName;
	if (-1 != GetFileAttributes(diskPath))
		return diskPath; 

	return WIN_PATH + strDllName;
}


bool CModule::LoadDll(CString strModulePath)
{
	if (GetFileAttributes(strModulePath) == -1)
	{
		GD_LOG(LOG_LVL_ERR,"can not find %s",strModulePath.GetBuffer());
		return false;
	}
	m_InsModule = LoadLibrary(strModulePath);

	if (!m_InsModule)
	{
		int nErrCode = GetLastError();
		GD_LOG(LOG_LVL_ERR,"LoadLibrary %s fail , err code: 0x%08x",strModulePath.GetBuffer(),nErrCode);
		return false;
	}

	GetAddressTable_t getAddressTable = NULL;
	getAddressTable = (GetAddressTable_t)GetProcAddress(m_InsModule,L"GetAddressTable");
	if (!getAddressTable)
	{
		GD_LOG(LOG_LVL_ERR,"get AddressTable fail");
		return false;
	}

	pExportInterface_ = getAddressTable();
	pExportInterface_->SendMsg = GetMsgFromModule; 
	pExportInterface_->GetOtherData = GetOtherModuleParam; 
	return true;

}


